package com.cn.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class WebSocketController
{

    @Autowired
    public SimpMessageSendingOperations simpMessageSendingOperations;//websocket发送请求到前台

    //访问html页面
    @GetMapping("/socket")
    public String socketHtml()
    {
        return "socket";
    }

    /**
     * 发送方法1
     * 是将接收的消息发给 /topic/notice
     */
    @ResponseBody
    @MessageMapping("/change-notice")//客户端访问服务端的时候config中配置的服务端接收前缀也要加上 例：/app/change-notice
    @SendTo("/topic/notice")//config中配置的订阅前缀记得要加上
    public String greeting(String message)
    {
        System.out.println("服务端接收到消息：" + message);
        return message;
    }

    @ResponseBody
    @RequestMapping(value = "/test", method = RequestMethod.GET)//客户端访问服务端的时候config中配置的服务端接收前缀也要加上 例：/app/change-notice
    public void message(String message)
    {
        Map<String, String> map = new HashMap<>();
        map.put("message", message);
        //这个方法是websocket给前台发送即时数据的
        simpMessageSendingOperations.convertAndSend("/topic/notice", JSONObject.toJSON(map));
    }
}
